package com.inspur.dgov.policy.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.inspur.dgov.bsp.system.entity.PubDict;
import com.inspur.dgov.bsp.system.feign.ISystemFeign;
import com.inspur.dgov.common.tool.api.R;
import com.inspur.dgov.policy.entity.FilePolicy;
import com.inspur.dgov.policy.entity.InfoPolicy;
import com.inspur.dgov.policy.entity.PolicySubjectRelation;
import com.inspur.dgov.policy.feign.IEsPolicyFeign;
import com.inspur.dgov.policy.mapper.EsPolicyMapper;
import com.inspur.dgov.policy.service.EsPolicyService;
import com.inspur.dgov.policy.service.FilePolicyService;
import com.inspur.dgov.policy.service.InfoPolicyService;
import com.inspur.dgov.policy.service.PolicySubjectRelationService;
import com.inspur.dgov.policy.vo.EsPolicyVO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * ES政策信息 服务实现类
 *
 * @Author chengxin.ju
 * @Date 20/3/18
 * @Version 1.0
 * @Description ES政策信息 服务实现类
 */
@Slf4j
@Service
@AllArgsConstructor
public class EsPolicyServiceImpl extends ServiceImpl<EsPolicyMapper, EsPolicyVO> implements EsPolicyService {

    @Autowired
    private InfoPolicyService infoPolicyService;

    @Autowired
    private FilePolicyService filePolicyService;

    @Autowired
    private PolicySubjectRelationService policySubjectRelationService;

    @Autowired
    private IEsPolicyFeign esPolicyFeign;

    @Autowired
    private ISystemFeign systemFeign;

    /**
     * 插入数据到ES
     * @return
     */
    @Override
    public R insertEsPolicy(String policyId) {
        InfoPolicy policy = this.infoPolicyService.getById(policyId);
        EsPolicyVO policyVO = this.buildEsPolicy(policy);
        return this.esPolicyFeign.insert((JSONObject)JSON.toJSON(policyVO));
    }

    /**
     * 更新数据到ES
     * @return
     */
    @Override
    public R updateEsPolicy(String policyId) {
        InfoPolicy policy = this.infoPolicyService.getById(policyId);
        EsPolicyVO policyVO = this.buildEsPolicy(policy);
        return this.esPolicyFeign.update((JSONObject)JSON.toJSON(policyVO));
    }

    /**
     * 更新政策专题到ES
     * @return
     */
    @Override
    public R updateEsPolicySubject(List<PolicySubjectRelation> list) {
        JSONArray bulkArray = new JSONArray();
        for (PolicySubjectRelation relation : list) {
            JSONObject policyVO = new JSONObject();
            policyVO.put("id", relation.getPolicyId());
            //政策专题关系
            QueryWrapper<PolicySubjectRelation> queryWrapper = new QueryWrapper();
            queryWrapper.lambda().eq(PolicySubjectRelation::getPolicyId, relation.getPolicyId());
            List<PolicySubjectRelation> rlist = this.policySubjectRelationService.list(queryWrapper);
            JSONArray relationArray = new JSONArray();
            for (PolicySubjectRelation rel : rlist) {
                JSONObject obj = new JSONObject();
                obj.put("subject", rel.getSubjectId());
                relationArray.add(obj);
            }
            policyVO.put("extendSpecialSubject", relationArray);
            bulkArray.add(policyVO);
        }
        JSONObject param = new JSONObject();
        param.put("bulkArray", bulkArray);
        return this.esPolicyFeign.updateBatch(param);
    }

    /**
     * 从ES删除数据
     * @return
     */
    @Override
    public R deleteEsPolicy(String policyId) {
        JSONObject obj = new JSONObject();
        obj.put("id", policyId);
        return this.esPolicyFeign.delete(obj);
    }

    private Date formatDate(String str) {
        try {
            return DateUtil.parse(str, "yyyy-MM-dd");
        } catch (Exception e) {
            return null;
        }
    }

    private EsPolicyVO buildEsPolicy(InfoPolicy policy) {
        EsPolicyVO policyVO = new EsPolicyVO();
        //处理字段
        //ID
        policyVO.setId(StrUtil.nullToEmpty(policy.getId()));
        //标题
        policyVO.setBasicTitle(StrUtil.nullToEmpty(policy.getBasicTitle()));
        //发文编号
        policyVO.setBasicIssuedNumber(StrUtil.nullToEmpty(policy.getBasicIssuedNumber()));
        //所属区划名称
        policyVO.setRegionName(StrUtil.nullToEmpty(policy.getRegionName()));
        //所属区划编码
        policyVO.setRegionCode(StrUtil.nullToEmpty(policy.getRegionCode()));
        //所属部门名称
        policyVO.setOrgName(StrUtil.nullToEmpty(policy.getOrgName()));
        //所属部门编码
        policyVO.setOrgCode(StrUtil.nullToEmpty(policy.getOrgCode()));
        //发文部门
        policyVO.setBasicDepartmentName(StrUtil.nullToEmpty(policy.getBasicDepartmentName()));
        //信息来源
        policyVO.setBasicSourceUrl(StrUtil.nullToEmpty(policy.getBasicSourceUrl()));
        //发文日期
        String basicReleaseDate = policy.getBasicReleaseDate();
        Date releaseDate = formatDate(basicReleaseDate);
        if (null != releaseDate) {
            policyVO.setBasicReleaseDate(releaseDate);
        }
        //主题词
        String[] subWords = StrUtil.split(StrUtil.nullToEmpty(policy.getBasicSubjectWords()), ",");
        JSONArray subWordArray = new JSONArray();
        for (String subWord : subWords) {
            JSONObject obj = new JSONObject();
            obj.put("word", subWord);
            subWordArray.add(obj);
        }
        policyVO.setBasicSubjectWords(subWordArray);
        //主题分类
        String classification = policy.getBasicSubjectClassification();
        JSONArray classificationsArray = new JSONArray();
        if (StrUtil.isNotBlank(classification)) {
            List<PubDict> dictList = this.systemFeign.dictListByIds(classification).getData();
            Map<Long, List<PubDict>> map = dictList.stream().collect(Collectors.groupingBy(item -> {
                if (item.getParentId() == null) {
                    return 0L;
                }
                return item.getParentId();
            }));
            for (Map.Entry<Long, List<PubDict>> entry : map.entrySet()) {
                Long key = entry.getKey();
                List<PubDict> value = entry.getValue();
                if (key.equals(0L)) {
                    value.stream().forEach(dict -> {
                        JSONObject subjectObj = new JSONObject();
                        JSONArray classArray = new JSONArray();
                        JSONObject classObj = new JSONObject();
                        classObj.put("classification", dict.getId());
                        classArray.add(classObj);
                        subjectObj.put("subject", classArray);
                        classificationsArray.add(subjectObj);
                    });
                } else {
                    JSONObject subjectObj = new JSONObject();
                    JSONArray classArray = new JSONArray();
                    value.stream().forEach(dict -> {
                        JSONObject classObj = new JSONObject();
                        classObj.put("classification", dict.getId());
                        classArray.add(classObj);
                    });
                    subjectObj.put("subject", classArray);
                    classificationsArray.add(subjectObj);
                }
            }
        }
        policyVO.setBasicSubjectClassification(classificationsArray);
        //政策文本ID
        policyVO.setBasicContentId(StrUtil.nullToEmpty(policy.getBasicContentId()));
        //附件链接地址
        policyVO.setBasicAttachementUrl(StrUtil.nullToEmpty(policy.getBasicAttachementUrl()));
        //采集方式
        policyVO.setCollectStyle(StrUtil.nullToEmpty(policy.getCollectStyle()));
        //采集者ID
        policyVO.setCollecterId(StrUtil.nullToEmpty(policy.getCollecterId()));
        //采集者姓名
        policyVO.setCollecterName(StrUtil.nullToEmpty(policy.getCollecterName()));
        //采集租户
        policyVO.setCollectTenant(StrUtil.nullToEmpty(policy.getCollectTenant()));
        //收集时间
        String collectDate = policy.getCollectDate();
        Date cDate = formatDate(collectDate);
        if (null != cDate) {
            policyVO.setCollectDate(cDate);
        }
        //状态
        policyVO.setBasicState(StrUtil.nullToEmpty(policy.getBasicState()));
        //系统状态
        policyVO.setBasicStatus(StrUtil.nullToEmpty(policy.getBasicStatus()));
        //主题分类修正
        policyVO.setExtendSubjectUpdate(StrUtil.nullToEmpty(policy.getExtendSubjectUpdate()));
        //文件类型
        policyVO.setExtendDocType(StrUtil.nullToEmpty(policy.getExtendDocType()));
        //关键词
        String extendKeywords = StrUtil.nullToEmpty(policy.getExtendKeywords());
        String[] keywords = extendKeywords.split(",|，");
        JSONArray words = new JSONArray();
        for (String word: keywords) {
            JSONObject obj = new JSONObject();
            obj.put("keyword", word);
            words.add(obj);
        }
        policyVO.setExtendKeywords(words);
        //生效日期
        LocalDate useDate = policy.getExtendUseDate();
        if (null != useDate) {
            policyVO.setExtendUseDate(useDate);
        }
        //摘要
        policyVO.setExtendSummary(StrUtil.nullToEmpty(policy.getExtendSummary()));
        //面向对象
        String[] extCorporations = StrUtil.split(StrUtil.nullToEmpty(policy.getExtendCorporation()), ",");
        JSONArray corporations = new JSONArray();
        for (String corporation : extCorporations) {
            JSONObject obj = new JSONObject();
            obj.put("corporation", corporation);
            corporations.add(obj);
        }
        policyVO.setExtendCorporation(corporations);
        //扩展1
        policyVO.setExtendRedundantfield1(StrUtil.nullToEmpty(policy.getExtendRedundantField1()));
        //扩展2
        policyVO.setExtendRedundantField2(StrUtil.nullToEmpty(policy.getExtendRedundantField2()));
        //扩展3
        policyVO.setExtendRedundantField3(StrUtil.nullToEmpty(policy.getExtendRedundantField3()));
        //扩展4
        policyVO.setExtendRedundantField4(StrUtil.nullToEmpty(policy.getExtendRedundantField4()));
        //扩展5
        policyVO.setExtendRedundantField5(StrUtil.nullToEmpty(policy.getExtendRedundantField5()));
        //最后修改时间
        LocalDateTime modifyDate = policy.getModifyTime();
        if (null != modifyDate) {
            policyVO.setModifyTime(modifyDate);
        }

        policyVO.setBasicTitle(policy.getBasicTitle());
        FilePolicy file = this.filePolicyService.getById(policy.getBasicContentId());
        String content = file.getContentHtml();
        content = StrUtil.removeAll(content, '\r', '\n', ' ').replaceAll("<p>", "").replaceAll("</p>", "");
        policyVO.setExtendContent(content);
        //政策专题关系
        QueryWrapper<PolicySubjectRelation> queryWrapper = new QueryWrapper();
        queryWrapper.lambda().eq(PolicySubjectRelation::getPolicyId, policy.getId());
        List<PolicySubjectRelation> list = this.policySubjectRelationService.list(queryWrapper);
        JSONArray relationArray = new JSONArray();
        for (PolicySubjectRelation relation : list) {
            JSONObject obj = new JSONObject();
            obj.put("subject", relation.getSubjectId());
            relationArray.add(obj);
        }
        policyVO.setExtendSpecialSubject(relationArray);

        //关联政策ID
        String[] parentIds = StrUtil.split(StrUtil.nullToEmpty(policy.getParentId()), ",");
        JSONArray parentIdArray = new JSONArray();
        for (String parentId : parentIds) {
            JSONObject obj = new JSONObject();
            obj.put("id", parentId);
            parentIdArray.add(obj);
        }
        policyVO.setParentId(parentIdArray);
        //政策类型
        policyVO.setPolicyType("policy");
        return policyVO;
    }
}
